<template>
    <tm-app class="content d-flex d-c a-center" color="#ffffff" :style="{ paddingTop: '44px' }">
        <image
            class="logo psr"
            src="../../static/logo2.png"
            mode=""
        ></image>
        <view class="bottomBox d-flex d-c a-center j-center" v-if="NETWORK.statu&&!isUpdateing">
            <view class="btn d-flex a-center j-center" @tap="wxlogin">
                    <view class="icon_content d-flex a-center j-center">
                        <i class="icon icon-weixin"></i>
                    </view>
                    
                    <text>微信登录</text>
            </view>
            <view class="phone_login d-flex a-center j-center" @tap="goPhoneLogin">
                    <view class="icon_content d-flex a-center j-center">
                        <i class="phone_icon tmicon tmicon-md-phone-portrait"></i>
                    </view>
                    
                    <text class="text">手机登录</text>
            </view>

            <tm-checkbox
                class="check"
                outlined
                v-model="readed"
                :size="30"
                :font-size="22"
                @change="handleCheck"
                color="#23e2a6"
                :value="true"
                label=""
            >
                <view class="read">
                    我已阅读并同意<text class="uline" @tap="goUserAgreement">《用户协议》</text>、<text class="uline" @tap="goPrivacyPolicy">《隐私协议》</text>
                </view>
             
            </tm-checkbox>


        </view>

        <agree ref="agree_ref" @agree="handleAgree"></agree>
        <view v-if="!NETWORK.statu||isUpdateing" class="update d-flex d-c a-center j-center">
            <view class="progress_box" v-show="NETWORK.statu">
                <progress class="progress" border-radius="35" :percent="percent" activeColor="#23e2a6" :show-info="false" stroke-width="10" />
            </view>
            <view class="statu_text d-flex a-center j-center">
                <text>{{statu_text}}</text>
                <image v-if="syncApp" style="width:36rpx;height:36rpx;margin-left:10rpx;"  src="/static/grey.gif"></image>
            </view>
        </view>

    </tm-app>
</template>

<script setup lang="ts">
import { computed, nextTick, ref } from "vue";
import { onShow, onLoad,onUnload } from "@dcloudio/uni-app";
import { wxAuth, getUserDetail, checkUpdate,checkV } from "@/api/api";
import { getAppVersion, getPlatform } from "@/utils/utils";
import { imLogin } from "@/hooks/imLogin";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import agree from "@/components/agree.vue";

import { userData as userDataStore } from "@/store/userData";
import { config as configStore } from "@/store/config";
import { ver } from "@/store/ver";
import { network } from "@/store/network";
import { checkNet } from "@/utils/utils";

const systemInfo: any = systemInfoStore();

const readed = ref(false);
const msg: any = ref();

const NETWORK = network();

const VER = ver();

const config: any = configStore();
const handleCheck = (bool:Boolean) => {
    config.setConfig({agreement:bool});
};
const userData: any = userDataStore();

const goPhoneLogin = () => {
    uni.navigateTo({
        url: "/pages/phoneLogin/phoneLogin",
    });
};


let checkNetInt:any = null;

const setCheckNetInt=()=>{
    checkNetInt = setInterval(async()=>{
        let bool = await checkNet() as boolean;
        NETWORK.setNet(bool);
    },1000)
}


const clearCheckNetInt = ()=>{
    clearInterval(checkNetInt);
    checkNetInt = null;
}



const goUserAgreement = ()=>{
    uni.navigateTo({
		url:`/pages/webview/webview?title=用户协议&url=http://52pp365.com/yonghuxieyi.html`
	});
}

const goPrivacyPolicy = ()=>{
    uni.navigateTo({
		url:`/pages/webview/webview?title=隐私政策&url=http://52pp365.com/yinsizhengce.html`
	});
}

const GetUserData = async (userId: string) => {
    const detail: any = await getUserDetail({ id: userId });
	console.log(detail)
    const { flag, data } = detail;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: '获取用户信息失败，请稍后再试',
            duration: 1500,
        });
        return
    }
    //const { id, nickName, openid, photo, sex, phone } = data;
	const { photo } = data;
    userData.clearUserData();
    if(photo){
        userData.setUserData(data);
        uni.setStorageSync('USER_DATA',data);
    }
    return data;
};

const wxlogin = async() => {
    if (!readed.value) {
        const bool = await agree_ref.value.open1();
        if(!bool){
            return;
        }
    }

    uni.login({
        provider: "weixin",
        onlyAuthorize: true, // 微信登录仅请求授权认证
        async success(event) {
			console.log(event.code)
            const res: any = await wxAuth({ code: event.code });
            const { flag, data } = res;

            console.log('weixin login');
            console.log('weixin login');
            console.log('weixin login');
            console.log(res);

            if (flag !== 1) {
                uni.showToast({
                    icon: "none",
                    title: res.message,
                    duration: 1500,
                });
                return
            }

            const { id, token } = data;
            uni.setStorageSync("api_token", token);

            const obj = await GetUserData(id);
			console.log(obj)
            if (obj.phone) {
                uni.setStorageSync("api_token", token);
                imLogin(userData.id,null);
            } else {
                uni.setStorageSync("FIRST_USERDATA", JSON.stringify(obj));

                uni.navigateTo({
                    url: `/pages/bindPhone/bindPhone`,
                });
            }
            // if(bool){
            //     imLogin(userData.id);
            // }
        },
        fail: function (err) {
            console.log(err);
            // 登录授权失败
            // err.code是错误码
        },
    });
};


const agree_ref = ref();
const isUpdateing = ref(false);
const updateStatu = ref('');
const percent = ref(0);

const syncApp = ref(false)

const statu_text = computed(()=>{

    if( !NETWORK.statu){
        return '没有网络'
    }

    if(syncApp.value){
        return '加载中'
    }

    if(updateStatu.value === 'download'){
        return '正在下载更新...'
    }

    if(updateStatu.value === 'update'){
        return '更新中...'
    }

    if(updateStatu.value === 'success'){
        return '更新成功,即将重启应用'
    }

    if(updateStatu.value === 'fail'){
        return '更新失败,请重试或重下载APP'
    }

    if(updateStatu.value === 'downloadfail'){
        return '下载更新失败,请检查网络'
    }

    return '即将更新...';
})


const handleAgree = ()=>{
    readed.value = true;
}

// const exit = ()=>{
//     plus.ios.import("UIApplication").sharedApplication().performSelector("exit");
// }

let verInt:any = null;


const hasNet = ref(false);


const gerV = async()=>{



    const res: any = await checkV({});

    const {flag, data} = res;
    if(flag!==1){
        throw new Error('gerv failed');
        //return;
    }

    const a:any[] = []
    const i:any[] = []

    data.forEach((item:any)=>{
        if(item.slimKey==='1'){
            a.push(item.slimValue)
        }
        if(item.slimKey==='2'){
            i.push(item.slimValue)
        }
    })



    //let arr = null;
	let arr:any[] = [];

    const platform = uni.getSystemInfoSync().platform;

    if(platform==='ios'){
        arr = i
    }else{
        arr = a
    }

    let currentVersion = '1.0.4';


    /*#ifdef APP-PLUS*/
    currentVersion = await getAppVersion() as string
    /*#endif*/


    const f = arr.some(item=>item===currentVersion)

    VER.setVer(f);


    if(f){
        isUpdateing.value = false;
        syncApp.value = false;
    }

}


const appUpdate = async (option: any) => {




    const {isHot,url} = option;

    if (isHot) {
        hasNet.value = true;
        nextTick(()=>{
            downloadNew(url)
        })

    }else{
		const platform = uni.getSystemInfoSync().platform;
		if(platform==='ios'){
		    plus.runtime.openURL('https://apps.apple.com/us/app/%E8%BD%BB%E7%9B%88/id6476827004');
		}else{
		    plus.runtime.openURL('https://sj.qq.com/appdetail/uni.UNI0670B83');
		}
    }

};

let installTime = 0;

let downloadTime = 0;

const downloadNew = (url:string)=>{


    updateStatu.value = 'download'

        const downloadTask = uni.downloadFile({
            url,
            success: (downloadResult) => {

                if(downloadResult.statusCode !== 200){
                    updateStatu.value = 'downloadfail'
                    return;
                }

                installNew(downloadResult);    
            },

            fail() {

                if(downloadTime<10){
                    downloadTime++;
                    downloadNew(url);
                }else{
                    updateStatu.value = 'downloadfail'
                    // uni.showToast({
                    //     icon: "error",
                    //     title: "下载更新失败",
                    //     duration: 1500,
                    // });

                }


            },
        });

        downloadTask.onProgressUpdate(res => {
				percent.value = res.progress;
				// this.downloadedSize = (res.totalBytesWritten / Math.pow(1024, 2)).toFixed(2);
				// this.packageFileSize = (res.totalBytesExpectedToWrite / Math.pow(1024, 2)).toFixed(2);
		});
		

}


const installNew = (downloadResult:any)=>{
    if (downloadResult.statusCode === 200) {
		/*#ifndef APP-PLUS*/
		isUpdateing.value = false;
		/*#endif*/
		updateStatu.value = 'update'
		plus.runtime.install(
			downloadResult.tempFilePath,
			{
				force: false,
			},
			function () {
				uni.hideLoading();
				updateStatu.value = 'success'
				// uni.showToast({
				//     icon: "success",
				//     title: "更新成功,请登录",
				//     duration: 1500,
				// });

				setTimeout(()=>{
					plus.runtime.restart();
				},1400)

			},
			function (e) {

				if(installTime<10){
					setTimeout(()=>{
						installTime++;
						installNew(downloadResult)
					},1000)
				}else{
					updateStatu.value = 'fail'
				}
			}
		);
	}
}


let ischeck = false


const CheckUpdate = async () => {
    if(ischeck){
        return;
    }

    ischeck = true;

    try{
        await gerV();


        if(VER.ver){
            return;
        }

        const platform = await getPlatform();
        const terminalSysterm = platform === "ios" ? "01" : "02";
        let currentVersion = '1.0.4';


        /*#ifdef APP-PLUS*/
        currentVersion = await getAppVersion() as string
        /*#endif*/
        const res:any = await checkUpdate({ terminalSysterm });

        if (res.flag !== 1) {
            return;
        }

        const { version } = res.data;

        // if(uni.getStorageSync(`ignore${version}`)){
        //     return;
        // }

        if (currentVersion !== version) {
            appUpdate(res.data);
        }else{
            isUpdateing.value = false;
        }


        nextTick(()=>{
            /*#ifdef APP-PLUS*/
            setTimeout(()=>{
                plus.navigator.closeSplashscreen();
            },2000)
            /*#endif*/
        })

        clearInterval(verInt)
        verInt=null
        
    }catch(e){

        ischeck=false;
        //TODO handle the exception
    }
};
onLoad((option:any) => {
	if((userData.id == null && userData.id == '') || (!NETWORK.statu||isUpdateing.value)){
		plus.navigator.closeSplashscreen();
	}
	uni.getPushClientId({
		success: (res) => {
			console.log(res.cid);
		},
		fail(err) {
			console.log(err)
		}
	})
    //uni.hideLoading();
	/*
    const token = uni.getStorageSync('api_token');
    setCheckNetInt();
    if(!token){
        setTimeout(()=>{
            plus.navigator.closeSplashscreen();
        },200)
    }else{
    }
    setTimeout(()=>{
            plus.navigator.closeSplashscreen();
    },10000)

	*/


    if(option.update&&!VER.ver){
        isUpdateing.value = true;
        const updatemsg = uni.getStorageSync('updatemsg');
        appUpdate(updatemsg)
    }

    if(!option.update){
        syncApp.value = true;
        CheckUpdate();
        verInt = setInterval(()=>{
            CheckUpdate();
        },1000)


    }
    /*#ifdef APP-PLUS*/
    if(plus.runtime.isAgreePrivacy()){
        readed.value = true;
        config.setConfig({agreement:true});
    }else{
        setTimeout(()=>{
            agree_ref.value.open();
        },1000)
    }
    /*#endif*/
});


onUnload(()=>{
    clearCheckNetInt();
})
onShow(() => {
    readed.value = config.agreement;
});
</script>

<style lang="scss" scoped>
.content {
    width: 100%;
    height: 100%;
    background: #fff;
    color: $slim-main;
}

.read{
    font-size:22rpx;
    color:#999;
    .uline{
        color: $slim-main;
    }
}

.logo {
    top: 300rpx;
    height: 141rpx;
    width: 412rpx;
}

.text-area {
    display: flex;
    justify-content: center;
    margin-bottom: 200rpx;
}

.title {
    font-size: 56rpx;
    color: $slim-main;
    margin-top: 20rpx;
}

.bottomBox {
    position: absolute;
    bottom: 90rpx;

    .textContent{
        width:180rpx;
    }
    .btn {
        margin-top: 20rpx;
        width: 570rpx;
        height: 86rpx;
        text-align: center;
        line-height: 86rpx;
        border-radius: 20rpx;
        background: $slim-main;
        color: #fff;
        font-size: 28rpx;
        .icon{
            font-size:40rpx;
            margin-right:5rpx;
        }
        &:active {
            opacity: 0.8;
        }
    }
    .check {
        margin-top: 50rpx;
    }
}

.update{
    position: absolute;
    bottom: 200rpx;
    .progress{
        width: 570rpx;
    }
    .progress_box{
        width: 570rpx;
        height:10px;
        border-radius:3px;
        overflow:hidden;
    }
    .statu_text{
        width:570rpx;
        color: #555;
        margin-top:5rpx;
        height:40rpx;
        font-size: 28rpx;
        text-align: center;
    }
}

.icon_content{
    width:50rpx;
    height:100%;
}

.phone_login {
    margin-top: 20rpx;
    width: 570rpx;
    height: 84rpx;
    text-align: center;
    line-height: 86rpx;
    border-radius: 20rpx;
    background:#fff;
    color: $slim-main;
    font-size: 28rpx;
    border:1px solid $slim-main;
    &:active {
        opacity: 0.8;
    }

    .phone_icon {
        font-size: 28rpx;
        margin-right: 5rpx;
    }
    .text {
        font-size: 28rpx;
    }
}

.popup_box{
    width:584rpx;
    height:710rpx;
    padding:45rpx;
    background: linear-gradient(27deg, #D6F6FC 0%, #EAFCE1 59%, #B2FACD 100%);
    border-radius: 20rpx;
    .u_line{
        text-decoration: underline;
        color:#1DC691;
    }
    .dun{
        width:100rpx;
        height:142rpx;
        margin:0 auto;
    }

    .title{
        color:#333;
        font-size:34rpx;
        margin-top:-10rpx;
    }

    .desp{
        color:#585859;
        font-size:26rpx;
        text-align: left;
        margin-top:20rpx;
    }

}
</style>
